﻿using AutoMapper;
using HuaweiCloud.Dotnet.Samples.Common;
using HuaweiCloud.Dotnet.Samples.ESports.Device.Component;
using HuaweiCloud.Dotnet.Samples.ESports.Device.Dto;
namespace HuaweiCloud.Dotnet.Samples.ESports.Device.Service
{
    public class StepService : DocCrudApplicationServiceBase<Step, CreateStepDto, CreateStepDto, StepDto>, IStepService
    {
        public StepService(IDocRepository<Step> repository, IMapper mapper) : base(repository, mapper)
        {
        }

        public override async Task AddAsync(CreateStepDto t, CancellationToken token = default)
        {
            var sDate = t.Date.Date;
            // 查询当天指定设备的记录，如果存在就更新，否则插入
            var eDate = sDate.AddSeconds(24 * 3600);
            var list = await _repository.ListAsync(x =>
                x.DeviceId == t.DeviceId
                && x.Date >= sDate
                && x.Date < eDate
                , token);
            if(list.Count > 0)
            {
                var temp = list[0];
                temp.Count = Math.Max(temp.Count, t.Count);
                temp.Date = t.Date;
                await _repository.UpdateAsync(temp, token);
            }
            else
            {
                await base.AddAsync(t, token);
            }
        }
    }
}
